package net.tmaize.dao.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import net.tmaize.dao.LatestDao;
import net.tmaize.entity.List_news;
import net.tmaize.entity.List_top_stories;
import net.tmaize.entity.News_latest;
import net.tmaize.utils.ApiUtils;
import net.tmaize.utils.JsonUtils;
import net.tmaize.utils.UrlUtils;

public class LatestDaoImpl implements LatestDao {

	private String jsonStr = null;
	
	@Override
	public News_latest getLatest() throws JSONException, IOException {

		jsonStr = JsonUtils.getJsonStr(ApiUtils.latestURL);
		
		News_latest latest = new News_latest();
		List<List_news> news = new ArrayList<List_news>();
		List<List_top_stories> top_stories = new ArrayList<List_top_stories>();

		JSONTokener jsonTokener = new JSONTokener(jsonStr);
		JSONObject jsonObject = new JSONObject(jsonTokener);

		latest.setDate(jsonObject.getString("date"));
		latest.setIs_today(jsonObject.getString("is_today"));
		latest.setDisplay_date(jsonObject.getString("display_date"));

		JSONArray jsonArray1 = jsonObject.getJSONArray("news");
		for (int i = 0; i < jsonArray1.length(); i++) {
			JSONObject jb = jsonArray1.getJSONObject(i);
			String title = jb.getString("title");
			String url = jb.getString("url");
			String image = jb.getString("image");
			String share_url = jb.getString("share_url");
			String thumbnail = jb.getString("thumbnail");
			String ga_prefix = jb.getString("ga_prefix");
			String id = jb.getString("id");
			news.add(new List_news(title, url, UrlUtils.imageUrlChange_1(image), share_url,UrlUtils.imageUrlChange_1(thumbnail), ga_prefix, id));
		}
		latest.setNews(news);

		JSONArray jsonArray2 = jsonObject.getJSONArray("top_stories");
		for (int i = 0; i < jsonArray2.length(); i++) {
			JSONObject jb = jsonArray2.getJSONObject(i);
			String image_source = jb.getString("image_source");
			String title = jb.getString("title");
			String url = jb.getString("url");
			String image = jb.getString("image");
			String share_url = jb.getString("share_url");
			String ga_prefix = jb.getString("ga_prefix");
			String id = jb.getString("id");
			top_stories.add(new List_top_stories(image_source, title, url, UrlUtils.imageUrlChange_1(image), share_url,ga_prefix, id));
		}
		latest.setTop_stories(top_stories);
		return latest;
	}
}
